<template>
    <Modal v-model:visible="isShowModal" :title="`${isEdit ? '编辑' : '添加'}成员`" @ok="handleOk" @cancel="handleCancel"
        ok-text="提交" cancel-text="取消" :loading="loading">
        <Form :model="formState" ref="formRef" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }" :rules="rules">
            <FormItem label="姓名" name="name">
                <Input v-model:value="formState.name" placeholder="请输入姓名" allowClear></Input>
            </FormItem>
            <FormItem label="手机号" name="mobile">
                <Input v-model:value="formState.mobile" placeholder="请输入手机号" allowClear></Input>
            </FormItem>
            <FormItem label="部门" name="departmentId">
                <Select v-model:value="formState.departmentId" style="width: 100%" placeholder="请选择部门" allowClear
                    @change="handleDepartment">
                    <SelectOption :value="item.departmentId" :key="item.departmentId" v-for="item in departmentOption">
                        {{ item.departmentName }}
                    </SelectOption>
                </Select>
            </FormItem>
            <FormItem label="岗位" name="jobId">
                <Select v-model:value="formState.jobId" placeholder="请选择岗位" allowClear>
                    <SelectOption :value="item.jobId" :key="item.jobId" v-for="item in positionOption">
                        {{ item.jobName }}
                    </SelectOption>
                </Select>
            </FormItem>
            <FormItem label="岗位名称" name="position">
                <Input v-model:value="formState.position" placeholder="请输入岗位名称" allowClear></Input>
            </FormItem>
            <FormItem label="是否超管" name="isAdmin">
                <RadioGroup v-model:value="formState.isAdmin" :options="EnumIsAdminUser" />
            </FormItem>
        </Form>
    </Modal>
</template>

<script lang="ts" setup>
import { Modal, Form, Input, message, Select, RadioGroup } from 'ant-design-vue'
import { Rule } from 'ant-design-vue/es/form';
import { EnumIsAdminUser } from './index'
import { CompanyApi, CompanyUserAddRequest, UserSearchResult } from '@/api';

const FormItem = Form.Item;
const SelectOption = Select.Option;

const emit = defineEmits(['ok']);

const isShowModal = ref(false)
const loading = ref(false)
const companyId = ref();
const editId = ref();
const isEdit = ref(false)
const formState = ref<CompanyUserAddRequest>({
    name: '',
    mobile: '',
    isAdmin: true,
})
const formRef = ref()
const rules: Record<string, Rule[]> = {
    name: [{ required: true, message: "请输入姓名", trigger: 'blur' }],
    mobile: [{ required: true, message: "请输入手机号", trigger: 'blur' }],
};
const departmentOption = ref()
const positionOption = ref();

const handleOpen = (data: { isEdit: boolean, id?: number, user?: UserSearchResult }) => {
    handleEmpty();
    isEdit.value = data.isEdit;
    companyId.value = data.id;

    if (data.isEdit && data.user) {
        let user = data.user
        editId.value = user.id;
        formState.value = {
            name: user.name || '',
            mobile: user.mobile || '',
            departmentId: user.departmentId,
            jobId: user.jobId,
            position: user.position,
            isAdmin: user.isAdmin,
        };
    }
    getDarpmentOption();
    isShowModal.value = true;
}


// 获取部门岗位二级列表
async function getDarpmentOption() {
    let res = await CompanyApi.companyGetdepartmentjobs(companyId.value);
    departmentOption.value = res;

    if (formState.value.departmentId) {
        let curDepartment = res.find(v => v.departmentId === formState.value.departmentId)?.jobs
        positionOption.value = curDepartment;
    }
}


// 部门选择
function handleDepartment(id: any) {
    positionOption.value = departmentOption.value.filter((v: any) => v.departmentId === id)[0].jobs
    formState.value.jobId = undefined;
}

const handleOk = () => {
    loading.value = true;
    formRef.value
        .validate()
        .then(async () => {
            if (isEdit.value) {
                message.success('修改成功')
                await CompanyApi.companyCompanyuserupdate(editId.value, formState.value)
            } else {
                await CompanyApi.companyCompanyuseradd(companyId.value, formState.value)
                message.success('添加成功')
            }

            emit('ok')
            handleClose();
        })
        .catch((err: any) => {
            console.log('校验失败', err);
        }).finally(() => {
            loading.value = false;
        });
}

const handleEmpty = () => {
    companyId.value = undefined
    formState.value = {
        name: '',
        mobile: '',
        isAdmin: true,
    };
}

function handleClose() {
    isShowModal.value = false;
}

function handleCancel() {
    handleEmpty();
    handleClose();
}

defineExpose({ handleOpen })
</script>